import { useEffect, Component } from "react";
import { connect } from "react-redux";
import { useNavigate, Navigate } from "react-router-dom";
import { addFlashMessage } from "../store/actions/flashMessages";

/* class组件写法 */
class myWithRouter extends Component {
  componentDidMount(){
    if (!this.props.isAuthenticated) {
      this.props.addFlashMessage({
        type: "danger",
        text: "请先登录",
      });
    };
  }
  render() {
    const Compose = this.props.child;
    return (
      <>
        <Compose {...this.props} />
       {!this.props.isAuthenticated && (<Navigate to="/login" replace={true} />)}
      </>
    )
  }
};

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.auth.isAuthenticated,
  };
};
export default connect(mapStateToProps, { addFlashMessage })(myWithRouter);

/* 函数组件写法 */
// const myWithRouter = () => (props) => {
//   const Compose = props.child;
//   const history = useNavigate();
//   useEffect(() => {
//     if (!props.isAuthenticated) {
//       props.addFlashMessage({
//         type: "danger",
//         text: "请先登录",
//       });
//       history("/login");
//     };
//   }, []);
//   return <Compose {...props} history={history} />;
// };

// export default connect(mapStateToProps, { addFlashMessage })(myWithRouter());
